<template>
  <div class="app-container">
    <div class="page-card">
      <div class="page-form">
        <el-input
          v-model="queryParams.groupName"
          placeholder="选科名称"
          clearable
          @input="handleSearch"
        />
        <el-input
          v-model="queryParams.groupRule"
          placeholder="选科规则名称"
          clearable
          @input="handleSearch"
        />
      </div>
      <el-table
        stripe
        border
        ref="tableList"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <!-- <el-table-column
          type="selection"
          width="55"
          align="center"
          :reserve-selection="true"
        /> -->
        <el-table-column
          label="选科名称"
          align="center"
          prop="groupName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="选科规则"
          align="center"
          prop="groupRule"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="必考科目"
          align="center"
          prop="examSubjectsName"
        >
          <template slot-scope="scope">
            <km-tag :option="scope.row.examSubjectsName" separator=" "></km-tag>
          </template>
        </el-table-column>
        <el-table-column label="选考科目" align="center" prop="tokenId">
          <template slot-scope="scope">
            <p
              style="margin: 0"
              v-for="(item, index) in scope.row.basicSubjectGroupSubSubjectName"
              :key="scope.$index + '_' + index"
            >
              选考{{ index + 1 }}科目：
              <km-tag :option="item" separator=" "></km-tag>
            </p>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="edit(scope.row)">编辑</el-link>
            <el-link type="danger" @click="del(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-bottom">
      <div class="sel-box">
        <p>共 {{ total }} 项</p>
        <el-button type="primary" @click="edit(false)" v-hasRole="['admin']"
          >添加选科</el-button
        >
        <!-- <el-button type="danger" :disabled="multiple" @click="del(false)"
          >批量删除</el-button
        > -->
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      ref="editDialog"
      class="editKmVisible"
      title="创建/编辑选科组"
      :visible.sync="editKmVisible"
      width="436px"
      :before-close="beforeClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="选科组名称" prop="groupName">
          <el-input v-model="editForm.groupName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="选科规则名称" prop="groupRuleId">
          <el-select v-model="editForm.groupRuleId">
            <el-option
              v-for="dict in selectClassification"
              :key="dict.id"
              :label="dict.modelffName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="必考科目" prop="examSubjects">
          <el-select v-model="editForm.examSubjects" multiple>
            <el-option
              v-for="dict in xklb"
              :key="dict.value"
              :label="dict.subjectName"
              :value="dict.subjectId"
            />
          </el-select>
        </el-form-item>

        <div v-for="(item, index) in editForm.basicChooseSubject" :key="index">
          <el-form-item
            :label="`选考${index + 1}科目`"
            :prop="`basicChooseSubject.${index}.selectSubjectIds`"
            :rules="[
              {
                required: true,
                message: '选考科目不能为空',
                trigger: 'change',
              },
            ]"
          >
            <el-select v-model="item.selectSubjectIds" multiple>
              <el-option
                v-for="dict in xklb"
                :key="dict.value"
                :label="dict.subjectName"
                :value="dict.subjectId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="`选考${index + 1}必选数`"
            :prop="`basicChooseSubject.${index}.selectRequiredCount`"
            :rules="[
              {
                required: true,
                message: '选考必选数不能为空',
                trigger: 'change',
              },
            ]"
          >
            <el-select v-model="item.selectRequiredCount">
              <el-option
                v-for="v in item.selectSubjectIds.length"
                :key="v"
                :label="v"
                :value="v"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="赋分开关">
            <el-switch
              v-model="item.selectScoreEnabled"
              active-color="#1890ff"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
            <el-button
              type="danger"
              size="mini"
              style="float: right; margin-right: 17px"
              @click="scxk(index)"
              >删除</el-button
            >
          </el-form-item>
        </div>

        <el-button type="primary" size="small" @click="tjxk"
          >添加选考科目</el-button
        >
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" @click="editSubmit" :loading="loading"
          >保 存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  grouplist,
  groupAdd,
  groupEdit,
  groupDel,
  endowlist,
} from "@/api/jcgl/xkgl";
import { subjectlistselect } from "@/api/common";
import { debounce } from "lodash";
export default {
  name: "Basic_xkgl",
  data() {
    return {
      firstLoad: true,
      loading: false,

      ids: [],

      pageNum: 1,
      pageSize: 15,
      total: 0,
      tableData: [],

      multiple: true,

      queryParams: {
        pageNum: 1,
        pageSize: 15,
        groupName: "",
        groupRuleId: "",
        groupRule: "",
      },

      xklb: [],
      editKmVisible: false,
      editForm: {
        groupName: "",
        groupRuleId: "",
        groupRule: "",
        examSubjects: [],
        basicChooseSubject: [],
      },
      rules: {
        groupName: [
          { required: true, message: "选科组名称不能为空", trigger: "blur" },
        ],
        groupRuleId: [
          {
            required: true,
            message: "选科规则名称不能为空",
            trigger: "change",
          },
        ],
        examSubjects: [
          { required: true, message: "必考科目不能为空", trigger: "change" },
        ],
      },

      selectClassification: [],
    };
  },
  created() {
    this.getList();
    subjectlistselect("-1").then((res) => {
      this.xklb = res.data;
    });

    endowlist().then((res) => {
      this.selectClassification = res.rows;
    });
  },
  activated() {
    if (!this.firstLoad) {
      this.getList();
    }
    this.firstLoad = false;
  },
  methods: {
    getList() {
      this.loading = true;
      this.tableData = [];
      grouplist(this.queryParams)
        .then((response) => {
          this.tableData = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    edit(row) {
      if (row) {
        this.editForm.id = row.id;
        this.editForm.groupName = row.groupName;
        this.editForm.groupRuleId = row.groupRuleId;
        if (row.basicChooseSubject) {
          this.editForm.basicChooseSubject = row.basicChooseSubject.map(
            (item) => {
              return {
                ...item,
                selectSubjectIds: item.selectSubjectIds
                  .split(",")
                  .map((item) => {
                    return Number(item);
                  }),
              };
            }
          );
        }
        if (row.examSubjects) {
          this.editForm.examSubjects = row.examSubjects
            .split(",")
            .map((item) => {
              return Number(item);
            });
        }
        if (row.select1Subjects) {
          this.editForm.select1Subjects = row.select1Subjects
            .split(",")
            .map((item) => {
              return Number(item);
            });
        }
        if (row.select2Subjects) {
          this.editForm.select2Subjects = row.select2Subjects
            .split(",")
            .map((item) => {
              return Number(item);
            });
        }
      }
      this.editKmVisible = true;
    },

    beforeClose(done) {
      this.editForm = {
        groupName: "",
        groupRuleId: "",
        groupRule: "",
        examSubjects: [],
        select1Subjects: [],
        basicChooseSubject: [],
      };
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let req;
          if (this.editForm.id) {
            req = groupEdit;
          } else {
            req = groupAdd;
          }

          let data = JSON.parse(JSON.stringify(this.editForm));
          data.examSubjects = this.editForm.examSubjects.join(",");
          data.basicChooseSubject.map((item) => {
            item.selectSubjectIds = item.selectSubjectIds.join(",");
          });

          data.groupRule = this.selectClassification.find((item) => {
            return item.id == data.groupRuleId;
          }).modelffName;

          req(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.handleClose();
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    del(id) {
      this.$modal.confirm("请确认进行删除操作").then(() => {
        groupDel(id ? id : this.ids).then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.$refs.tableList.clearSelection();
          this.ids = [];
          this.getList();
        });
      });
    },

    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 500),

    handleSearch() {
      this.debouncedSearch();
    },

    tjxk() {
      this.editForm.basicChooseSubject.push({
        selectSubjectIds: [],
        selectRequiredCount: "",
        selectScoreEnabled: "",
      });
    },
    scxk(index) {
      this.editForm.basicChooseSubject.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-select {
    width: 240px;
  }
}
</style>